<template>
  <view class="restaurant-layout">
    <!-- 区域选择 -->
    <view class="region-selector">
      <view 
        v-for="region in regions" 
        :key="region.regionId"
        class="region-item"
        :class="{ active: currentRegion === region.regionId }"
        @click="selectRegion(region.regionId)"
      >
        {{ region.regionName }}
      </view>
    </view>

    <!-- 餐桌布局区域 -->
    <view class="tables-layout">
      <view 
        v-for="board in boards" 
        :key="board.boardId"
        class="table-item"
        :class="getTableStatusClass(board.boardStatus)"
        @click="handleTableClick(board)"
      >
        <!-- 状态标签 -->
        <view class="status-badge">{{ getStatusText(board.boardStatus) }}</view>
        
        <!-- 主要信息区域 -->
        <view class="table-main">
          <view class="table-name">{{ board.boardName }}</view>
          <view class="table-info">
            <view class="info-item seats">
              <text class="icon">👥</text>
              <text>{{ board.seat }}人桌</text>
            </view>
            <view class="info-item type">
              <text class="icon">🏷️</text>
              <text>{{ board.boardType }}</text>
            </view>
          </view>
        </view>

        <!-- 用餐时长 -->
        <view 
          class="dining-duration" 
          :class="{ 'dining-active': calculateDiningDuration(board.boardId, board.boardStatus) !== '0分钟' && calculateDiningDuration(board.boardId, board.boardStatus) !== '' }"
        >
          <text class="icon">⏱️</text>
          <text>{{ calculateDiningDuration(board.boardId, board.boardStatus) }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { regionApi, boardApi, orderApi } from '../../utils/api'

// 数据状态
const regions = ref([])
const boards = ref([])
const currentRegion = ref(null)
const orders = ref({})
const allBoards = ref([])  // 存储所有餐桌数据
const allOrders = ref({})  // 存储所有订单数据

// 获取区域数据
const fetchRegions = async () => {
  try {
    console.log('开始获取区域数据')
    const result = await regionApi.getRegions(['9', '10'])
    console.log('区域数据响应:', result)
    
    if (result.code === 200) {
      // 添加一个包含所有区域的选项
      regions.value = [
        {
          regionId: 'all',
          regionName: '全部区域'
        },
        ...result.data
      ]
      if (regions.value.length > 0) {
        selectRegion(regions.value[0].regionId)
      }
    } else {
      throw new Error(result.message || '获取区域失败')
    }
  } catch (error) {
    console.error('获取区域列表出错:', error)
    uni.showToast({
      title: '获取区域列表失败',
      icon: 'none'
    })
  }
}

// 获取所有餐桌数据
const fetchAllBoards = async () => {
  try {
    console.log('开始获取所有餐桌数据')
    const result = await boardApi.getBoards([9, 10])
    console.log('餐桌数据响应:', result)
    
    if (result.code === 200) {
      allBoards.value = result.data
      filterBoards(currentRegion.value)
    } else {
      throw new Error(result.message || '获取餐桌失败')
    }
  } catch (error) {
    console.error('获取餐桌列表出错:', error)
    uni.showToast({
      title: '获取餐桌列表失败',
      icon: 'none'
    })
  }
}

// 获取所有订单数据
const fetchAllOrders = async () => {
  try {
    console.log('开始获取所有订单数据')
    const result = await orderApi.getRegionOrders([9, 10])
    console.log('订单数据响应:', result)
    
    if (result.code === 200) {
      // 将订单数据转换为以boardId为key的数组对象
      allOrders.value = result.data.reduce((acc, order) => {
        if (!acc[order.boardId]) acc[order.boardId] = []
        acc[order.boardId].push(order)
        return acc
      }, {})
      filterOrders(currentRegion.value)
    } else {
      throw new Error(result.message || '获取订单失败')
    }
  } catch (error) {
    console.error('获取订单列表出错:', error)
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    })
  }
}

// 根据区域筛选餐桌数据
const filterBoards = (regionId) => {
  if (regionId === 'all') {
    boards.value = allBoards.value
  } else {
    boards.value = allBoards.value.filter(board => board.regionId === Number(regionId))
  }
}

// 根据区域筛选订单数据
const filterOrders = (regionId) => {
  if (regionId === 'all') {
    orders.value = allOrders.value
  } else {
    // 获取该区域的所有餐桌ID
    const boardIds = allBoards.value
      .filter(board => board.regionId === Number(regionId))
      .map(board => board.boardId)
    
    // 筛选出这些餐桌的订单
    orders.value = Object.fromEntries(
      Object.entries(allOrders.value)
        .filter(([boardId]) => boardIds.includes(Number(boardId)))
    )
  }
}

// 选择区域
const selectRegion = (regionId) => {
  console.log('选择区域:', regionId)
  currentRegion.value = regionId
  filterBoards(regionId)
  filterOrders(regionId)
}

// 获取餐桌状态样式
const getTableStatusClass = (status) => {
  const statusMap = {
    'UNINHABITED': 'status-free',
    'BOOKING': 'status-reserved',
    'REPAST': 'status-occupied',
    'DISABLE': 'status-disabled'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'UNINHABITED': '空闲',
    'BOOKING': '已预订',
    'REPAST': '就餐中',
    'DISABLE': '停用'
  }
  return statusMap[status] || '未知'
}

// 计算就餐时长
const calculateDiningDuration = (boardId, boardStatus) => {
  if (boardStatus !== 'REPAST') return '0分钟'
  let orderList = orders.value[boardId]
  // 兼容老数据结构，若不是数组则转为数组
  if (!Array.isArray(orderList)) {
    orderList = orderList ? [orderList] : []
  }
  if (orderList.length === 0) return '0分钟'
  // 取placeOrderTime最接近当前时间且小于当前时间的那一条
  const now = new Date()
  let nearestOrder = null
  let minDiff = Infinity
  for (const order of orderList) {
    if (!order.placeOrderTime) continue
    const orderTime = new Date(order.placeOrderTime)
    const diff = now - orderTime
    if (diff >= 0 && diff < minDiff) {
      minDiff = diff
      nearestOrder = order
    }
  }
  if (!nearestOrder) return '0分钟'
  const startTime = new Date(nearestOrder.placeOrderTime)
  const diffMinutes = Math.floor((now.getTime() - startTime.getTime()) / (1000 * 60))
  if (diffMinutes < 0) return '时间错误'
  if (diffMinutes < 60) {
    return `${diffMinutes}分钟`
  } else {
    const hours = Math.floor(diffMinutes / 60)
    const minutes = diffMinutes % 60
    return `${hours}小时${minutes}分钟`
  }
}

// 处理餐桌点击
const handleTableClick = async (board) => {
  // 停用的餐桌不可点击
  if (board.boardStatus === 'DISABLE') {
    return
  }
  
  // 就餐中的餐桌跳转到订单详情页
  if (board.boardStatus === 'REPAST') {
    const order = orders.value[board.boardId]
    if (order) {
      try {
        // 获取订单菜品信息
        const result = await orderApi.getOrderItems(order.orderId)
        console.log('获取到的订单菜品信息:', result)
        
        if (result.code === 200) {
          // 将餐桌状态和菜品信息添加到订单数据中
          const orderWithDetails = {
            ...order,
            boardStatus: board.boardStatus,
            boardName: board.boardName,
            items: result.data
          }
          uni.navigateTo({
            url: `order-info?order=${JSON.stringify(orderWithDetails)}`
          })
        } else {
          throw new Error(result.message || '获取订单菜品信息失败')
        }
      } catch (error) {
        console.error('获取订单菜品信息出错:', error)
        uni.showToast({
          title: '获取订单菜品信息失败',
          icon: 'none'
        })
      }
    }
    return
  }
  
  // 其他状态（空闲、已预订）跳转到点餐页
  uni.navigateTo({
    url: `order?boardId=${board.boardId}`
  })
}

// 页面加载时获取数据
onLoad(() => {
  fetchRegions()
  fetchAllBoards()
  fetchAllOrders()
})

// 页面显示时刷新数据
onShow(() => {
  // 每次显示页面时都重新获取数据
  fetchAllBoards()
  fetchAllOrders()
})
</script>

<style lang="scss" scoped>
.restaurant-layout {
  min-height: 100vh;
  padding: 30rpx;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  .region-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 40rpx;
    padding: 20rpx;
    background: #ffffff;
    border-radius: 12rpx;

    .region-item {
      padding: 16rpx 32rpx;
      background-color: #f5f5f5;
      border-radius: 30rpx;
      font-size: 28rpx;
      color: #666;
      transition: all 0.3s ease;
      border: 2rpx solid transparent;

      &.active {
        background-color: #c70209;
        color: #fff;
      }
    }
  }

  .tables-layout {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320rpx, 1fr));
    gap: 30rpx;
    padding: 20rpx;

    .table-item {
      position: relative;
      padding: 40rpx 30rpx;
      border-radius: 16rpx;
      background-color: #ffffff;
      background-image: linear-gradient(135deg, rgba(0, 0, 0, 0.02) 25%, transparent 25%),
        linear-gradient(225deg, rgba(0, 0, 0, 0.02) 25%, transparent 25%),
        linear-gradient(45deg, rgba(0, 0, 0, 0.02) 25%, transparent 25%),
        linear-gradient(315deg, rgba(0, 0, 0, 0.02) 25%, transparent 25%);
      background-position: 10rpx 0, 10rpx 0, 0 0, 0 0;
      background-size: 20rpx 20rpx;
      background-repeat: repeat;
      min-height: 240rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      cursor: pointer;
      display: flex;
      flex-direction: column;

      &:hover {
        transform: translateY(-6rpx);
        box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);
      }

      // 状态标签样式
      .status-badge {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        padding: 6rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        font-weight: 600;
        background: rgba(0, 0, 0, 0.04);
        backdrop-filter: blur(5rpx);
      }

      // 主要信息区域
      .table-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 20rpx 0;

        .table-name {
          font-size: 48rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 30rpx;
          text-shadow: 1rpx 1rpx 1rpx rgba(0, 0, 0, 0.05);
        }

        .table-info {
          display: flex;
          gap: 20rpx;
          justify-content: center;
          
          .info-item {
            display: flex;
            align-items: center;
            gap: 8rpx;
            padding: 8rpx 16rpx;
            background: rgba(0, 0, 0, 0.04);
            border-radius: 12rpx;
            font-size: 26rpx;
            color: #666;

            .icon {
              font-size: 28rpx;
            }
          }
        }
      }

      // 用餐时长样式
      .dining-duration {
        margin-top: 20rpx;
        padding: 10rpx 20rpx;
        border-radius: 12rpx;
        background: rgba(0, 0, 0, 0.04);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8rpx;
        font-size: 24rpx;
        color: #666;
        backdrop-filter: blur(5rpx);

        .icon {
          font-size: 26rpx;
        }

        &.dining-active {
          color: #c70209;
          background: rgba(199, 2, 9, 0.08);
          font-weight: 600;
        }
      }

      // 状态相关样式
      &.status-free {
        .status-badge {
          color: #67c23a;
          background: rgba(103, 194, 58, 0.1);
        }
      }

      &.status-reserved {
        .status-badge {
          color: #c70209;
          background: rgba(199, 2, 9, 0.1);
        }
      }

      &.status-occupied {
        .status-badge {
          color: #FF3B30;
          background: rgba(255, 59, 48, 0.1);
        }
      }

      &.status-disabled {
        opacity: 0.8;
        cursor: not-allowed;
        
        .status-badge {
          color: #999;
          background: rgba(0, 0, 0, 0.08);
        }

        &:hover {
          transform: none;
          box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .tables-layout {
      grid-template-columns: repeat(auto-fill, minmax(280rpx, 1fr));
      gap: 20rpx;
      
      .table-item {
        .table-main {
          .table-name {
            font-size: 40rpx;
          }
        }
      }
    }
  }

  @media screen and (max-width: 480px) {
    .tables-layout {
      grid-template-columns: 1fr;
      gap: 15rpx;
      
      .table-item {
        padding: 30rpx 20rpx;
        
        .table-main {
          .table-name {
            font-size: 36rpx;
            margin-bottom: 20rpx;
          }
        }
      }
    }
  }
}
</style>